import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, message, Divider, Form, Select, Input, DatePicker, Steps, Badge} from "antd";
import StandardTable from '../../../components/StandardTable';
import RegionalSelection from "../../Form/RegionalSelection";
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const Step = Steps.Step;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ inspection, global,loading }) => ({
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  resdata: inspection.resdata,
  remindData: inspection.remindData,
  loading: inspection.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }

  componentWillUnmount() {
    // clearInterval(this.timerID);
  }


  componentDidMount() {
    const { pageSize } = this.state;
    const { pagesquery, dispatch} = this.props;
    // 获取区域数据
    dispatch({
      type: 'global/fetch_select_district',
    })
    // 列表
    this.getDataList(pagesquery,pageSize,1);


  }


  // 安装点位事件
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }

  }


  getDataList(params,pageSize,currentPage) {
    const { dispatch } = this.props;
    dispatch({
      type: 'inspection/fetch_inspection_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        region:undefined,
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      inspectTime:undefined,
      inspectProject:undefined,
      region:{districtId:[],pointId:0},
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.inspectionId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.region && fieldsValue.region.districtId.length>0){
        fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
      }
      if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
        fieldsValue.pointId = fieldsValue.region.pointId;
      }
      if(fieldsValue.inspectTime){
        fieldsValue.inspectTime = [fieldsValue.inspectTime[0].unix() * 1000,fieldsValue.inspectTime[1].unix() * 1000]
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    let linkpath;
    switch (action) {
      case 'add':
        linkpath = `/inspection/supervise/detail/add`;
        break;
      case 'edit':
        linkpath = `/inspection/supervise/${detailInfoId}/edit`;
        break;
      case 'info':
        linkpath = `/inspection/supervise/${detailInfoId}/info`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}`,  query: { ...formValues, currentPage} });
  }

  // 导出
  handleActionExport = (type,id) => {

    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    if(!id && !selectedRows) return;
    const inspectionIds = id ? [id] : selectedRows;

    dispatch({
      type: 'inspection/action_inspection_export',
      payload: {
        inspectionIds
      },
    }).then(()=>{
      this.setState({
        selectedRows: [],
      });
    }).then(()=>{
      message.success("所选稽查信息已导出")
    })
  };

  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="稽查时间">
              {getFieldDecorator('createTime',{
                initialValue: pagesquery && pagesquery.inspectTime ? [moment(pagesquery.inspectTime[0]),moment(pagesquery.inspectTime[1])] : undefined,
              })(
                <RangePicker
                  // showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD"
                  placeholder={['开始时间', '结束时间']}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="项目">
              {getFieldDecorator('inspectProject',{
                initialValue: pagesquery && pagesquery.inspectProject ? pagesquery.inspectProject : undefined,
              })(
                <Select  allowClear={true} placeholder="请选择项目" style={{ width: '100%' }} >
                  {dictionaries.inspectProject && dictionaries.inspectProject.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={16} sm={24}>
            <FormItem label="区域点位">
              {getFieldDecorator('region',{
                initialValue: pagesquery && pagesquery.region ? pagesquery.region : {districtId:[],pointId:0},
              })(
                <RegionalSelection
                  districtData={selectSource.districtData}
                  pointData={selectSource.pointData}
                  onChange={this.handleSearchDistrict}
                />
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries } = this.props;
    const { selectedRows } = this.state;
    const inspectProject = dictionaries.inspectProject && dictionaries.inspectProject.length>0
      ? dictionaries.inspectProject.map(item=>item.label)
      :[];

    const columns = [
      {
        title: '稽查时间',
        dataIndex: 'inspectTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '区域',
        dataIndex: 'districtName',
      },
      {
        title: '点位',
        dataIndex: 'pointName',
      },
      {
        title: '项目',
        dataIndex: 'inspectProject',
        render: (text)=> (
          <span>{inspectProject[parseInt(text)-1]}</span>
        ),
      },
      {
        title: '处理人',
        dataIndex: 'rectifyManName',
      },
      {
        title: '稽查人',
        dataIndex: 'creatorName',
      },
      // {
      //   title: '状态',
      //   dataIndex: 'status',
      //   render: (text)=> (
      //     <span>{inspectStatus[parseInt(text)-1]}</span>
      //   ),
      // },
      {
        title: '操作',
        // width: 150,
        // fixed:'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10253'} >
              <a onClick={() => this.handleLink('info',row.inspectId)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10254'} >
              {row.status=="01" && <a onClick={() => this.handleLink('edit',row.inspectId)}>修改</a>}
              {row.status!=="01" && <span style={{color:'#ccc'}}>修改</span>}
            </Authorized>
          </Fragment>
        ),
      },
    ];


    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <div className={styles.tableListOperator}>
            <Authorized authority={'10252'} >
              <Button icon="plus" type="primary"  onClick={() => this.handleLink('add',null)}>
                发现问题
              </Button>
            </Authorized>
{/*            <Authorized authority={'10256'} >
              <Button type="default"
                      onClick={() => this.handleActionExport()}
                      disabled={selectedRows.length > 0 ? false : true}
              >
                导出
              </Button>
            </Authorized>*/}
          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="inspectId"
            // scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            // onSelectRow={this.handleSelectRows}
            expandedRowRender={record =>
                <Steps size="small" current={parseInt(record.status)-1}>
                  {dictionaries.inspectStatus && dictionaries.inspectStatus.map(item =>
                     <Step key={item.value} title={item.label} />
                  )}
                </Steps>
            }
            expandedRowKeys={resdata.list && resdata.list.length>0 ? resdata.list.map(e=>e.inspectId) : []}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
